﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WadViewer.Configuration;

namespace WadViewer.DomainModel
{
	/// <summary>
	/// Repository for WAD tables
	/// </summary>
	public class WadRepository
	{
		/// <summary>
		/// the accessor
		/// </summary>
		private StorageAccessor storageAccessor = null;

		private const string TraceLogsTableName = "WADLogsTable";
		private const string EventLogsTableName = "WADWindowsEventLogsTable";
		private const string PerfCountersTableName = "WADPerformanceCountersTable";

		/// <summary>
		/// Sets up the access to Windows Azure Table Storage
		/// </summary>
		/// <param name="baseAddress">url to table storage</param>
		/// <param name="accountName">account name</param>
		/// <param name="key">secret key</param>
		public void Setup(TableConnection connection)
		{
			this.storageAccessor = new StorageAccessor(connection.BaseAddress, connection.AccountName, connection.Key);
		}

		/// <summary>
		/// Retrieves the trace logs
		/// </summary>
		/// <param name="from">from date and time (inclusive)</param>
		/// <param name="to">end date and time (exclusive)</param>
		/// <param name="maxResult">maximum number of items to return</param>
		public IList<WadTraceLogEntity> RetrieveTraceLogs(DateTime from, DateTime to, int maxResult)
		{
			if (storageAccessor == null) throw new InvalidOperationException();

			return storageAccessor.Retrieve<WadTraceLogEntity>(TraceLogsTableName, from, to, maxResult).ToList();
		}

		/// <summary>
		/// Retrieves the event logs
		/// </summary>
		/// <param name="from">from date and time (inclusive)</param>
		/// <param name="to">end date and time (exclusive)</param>
		/// <param name="maxResult">maximum number of items to return</param>
		public IList<WadEventLogEntity> RetrieveEventLogs(DateTime from, DateTime to, int maxResult)
		{
			if (storageAccessor == null) throw new InvalidOperationException();

			return storageAccessor.Retrieve<WadEventLogEntity>(EventLogsTableName, from, to, maxResult).ToList();
		}

		/// <summary>
		/// Retrieves the performance counters
		/// </summary>
		/// <param name="from">from date and time (inclusive)</param>
		/// <param name="to">end date and time (exclusive)</param>
		/// <param name="maxResult">maximum number of items to return</param>
		public IList<WadPerfCounterEntity> RetrievePerfCounters(DateTime from, DateTime to, int maxResult)
		{
			if (storageAccessor == null) throw new InvalidOperationException();

			return storageAccessor.Retrieve<WadPerfCounterEntity>(PerfCountersTableName, from, to, maxResult).ToList();
		}
	}
}
